package com.xmu.edu.tisp.login;

import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;

import com.xmu.edu.tisp.database.BaseService;
import com.xmu.edu.tisp.database.Tables;
import com.xmu.edu.tisp.webservice.ServiceXmlParser;
import com.xmu.edu.tisp.webservice.WebServices;

public class LoginAction {
	public static int login(String userId, String password) {
		String result=null;
		try {
			result = WebServices.invokeService("checkIdentity", new String[] { "userId",
					"password" }, new String[] { userId, password });
		} catch (Exception e) {
			return 1;
		}
		if (result == null)
			return 0;

		// try to write user info to database
		ServiceXmlParser parser = new ServiceXmlParser(result);
		try {
			//String tableName = parser.getMasterAttributes(0).getAsString("type");
			List<ContentValues> cvs=parser.getArrays(0);
			for(ContentValues c:cvs)
				BaseService.insertOrUpdate(Tables.TB_PDA_WEB_ADDR,c);
			ContentValues cv = parser.getArrays(1).get(0);
			BaseService.insertOrUpdate(Tables.TB_PDA_USER,cv);
			return 2;

		} catch (Exception ex) {
			return 0;
		}
	}
	
	public static String getUserIdByName(String userName){
		String selection = "LOGIN_NAME=?";
		String pk=Tables.primaryKey(Tables.TB_PDA_USER);
		Cursor c=BaseService.getdb().query(Tables.TB_PDA_USER, new String[]{pk}, selection, new String[]{userName}, null, null, null);
		c.moveToNext();
		String userId = c.getString(c.getColumnIndex(pk));
		//System.out.println("userId:"+userId);
		c.deactivate();
		c.close();
		if(userId!=null)
			return userId;
		else
			return null;
	}
	
	public static String checkUserInfo(String userName,String pwd){
		String selection = "LOGIN_NAME=? and PASSWORD=?";
		String pk=Tables.primaryKey(Tables.TB_PDA_USER);
		Cursor c=BaseService.getdb().query(Tables.TB_PDA_USER, new String[]{pk,"TECHNICIAN_ID"}, selection, new String[]{userName,pwd}, null, null, null);
		String s=null;
		while(c.moveToNext())
		{
			s=c.getString(1);
		}
		//int num = c.getCount();
		//System.out.println("userId:"+userId);
		c.deactivate();
		c.close();
		/*if(num>0)
			return true;
		else
			return false;*/
		return s;
		
	}
}
